package com.zzzyh.springproject.utils;

import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Component
public class UpLoadUtil {

    private static final Logger logger = LoggerFactory.getLogger(UpLoadUtil.class);

    @Getter
    private Path root;

    private final ResourceLoader resourceLoader;

    public UpLoadUtil(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostConstruct
    public void init() {
        // 默认初始化逻辑，可以保留或移除
        String defaultStorageLocation = null;
        try {
            defaultStorageLocation = "upload";
            logger.info("Default storage location: {}", defaultStorageLocation);
            Path path = Paths.get(defaultStorageLocation);
            this.root = path;
            Files.createDirectories(path);
            logger.info("Initialized default upload directory: {}", root);
        } catch (IOException e) {
            logger.error("Could not initialize default folder for upload! Storage location: {}", defaultStorageLocation, e);
            throw new RuntimeException("Could not initialize default folder for upload!", e);
        }
    }

    public static String uploadImage(MultipartFile file, String storagePath) {
        if (file.isEmpty()) {
            logger.error("Failed to store empty file.");
            throw new RuntimeException("Failed to store empty file.");
        }
        try {
            String originalFilename = file.getOriginalFilename();
            String filenameWithoutExtension = originalFilename;
            String extension = "";
            int lastDotIndex = originalFilename.lastIndexOf('.');
            if (lastDotIndex != -1) {
                filenameWithoutExtension = originalFilename.substring(0, lastDotIndex);
                extension = originalFilename.substring(lastDotIndex);
            }
            String uniqueFileName = UUID.randomUUID().toString() + filenameWithoutExtension + extension;

            // 使用传入的路径构建目标路径
            Path targetLocation = Paths.get(storagePath).resolve(uniqueFileName);

            // 确保目标路径的所有父目录都存在
            Files.createDirectories(targetLocation.getParent());

            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            logger.info("File uploaded to: {}", targetLocation);
            return targetLocation.toString().replace("\\", "/");
        } catch (Exception e) {
            logger.error("Could not store the file. Error: {}", e.getMessage(), e);
            throw new RuntimeException("Could not store the file. Error: " + e.getMessage(), e);
        }
    }


}